import React, { useState, useEffect, useRef } from 'react';
import { View, FlatList, StyleSheet, Dimensions, Image, TouchableOpacity } from 'react-native';

const { width } = Dimensions.get('window');

const Carousel = ({ data }) => {
  const [currentIndex, setCurrentIndex] = useState(0);
  const flatListRef = useRef<FlatList>(null);

  useEffect(() => {
    // 自动切换图片
    const interval = setInterval(() => {
      setCurrentIndex((prevIndex) => (prevIndex + 1) % data.length);
    }, 3000); // 每3秒切换一次

    return () => clearInterval(interval);
  }, [data]);

  useEffect(() => {
    if (flatListRef.current) {
      flatListRef.current.scrollToIndex({ animated: true, index: currentIndex });
    }
  }, [currentIndex, flatListRef]);

  const renderItem = ({ item }) => (
    <TouchableOpacity style={styles.slide}>
      <Image source={{ uri: item.image }} style={styles.image} />
    </TouchableOpacity>
  );

  const renderIndicator = () => (
    <View style={styles.indicators}>
      {data.map((_, index) => (
        <View
          key={index}
          style={[styles.indicator, currentIndex === index && styles.activeIndicator]}
        />
      ))}
    </View>
  );

  return (
    <View style={styles.container}>
      <FlatList
        ref={flatListRef}
        data={data}
        horizontal
        pagingEnabled
        showsHorizontalScrollIndicator={false}
        snapToAlignment="center"
        decelerationRate="fast"
        onViewableItemsChanged={({ viewableItems }) =>
          setCurrentIndex(viewableItems[0]?.isFullyVisible ? viewableItems[0].index : currentIndex)
        }
        viewabilityConfig={{
          itemVisiblePercentThreshold: 50,
        }}
        renderItem={renderItem}
        keyExtractor={(item, index) => index.toString()}
        onMomentumScrollEnd={(event) => {
          if (flatListRef.current) {
            const newIndex = Math.round(event.nativeEvent.contentOffset.x / width);
            setCurrentIndex(newIndex);
          }
        }}
      />
      {renderIndicator()}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    height: 380,
    overflow: 'hidden',
  },
  slide: {
    width,
    justifyContent: 'center',
    alignItems: 'center',
  },
  image: {
    width: '100%',
    height: '100%',
    resizeMode: 'cover',
  },
  indicators: {
    flexDirection: 'row',
    position: 'absolute',
    bottom: 10,
    left: 0,
    right: 0,
    justifyContent: 'center',
  },
  indicator: {
    width: 8,
    height: 8,
    borderRadius: 4,
    marginHorizontal: 4,
    backgroundColor: '#ccc',
  },
  activeIndicator: {
    backgroundColor: '#fff',
  },
});

export default Carousel;